package com.aiyige.page.publish.normalvideo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.NormalVideoModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.NormalVideoModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.page.interest.model.Interest;
import com.aiyige.page.interest.selectpublishinterest.SelectPublishInterestPage;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.inputintroduction.InputIntrodutionPage;
import com.aiyige.page.publish.normalvideo.adapter.InterestAdapter;
import com.aiyige.page.publish.normalvideo.model.PublishNormalVideoFormModel;
import com.aiyige.page.publish.normalvideo.model.PublishNormalVideoItem;
import com.aiyige.page.publish.selectvideocover.SelectVideoCoverPage;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.TrackUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.EditTextAutoMoveCursorToEndFocusChangeListener;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ExcludeEmojiInputFilter;
import com.aiyige.utils.ExcludeEnterInputFilter;
import com.aiyige.utils.ExcludeSpaceInputFilter;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.GlideUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UUIDUtil;
import com.aiyige.utils.VideoUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.aiyige.utils.widget.RoundCornerImageView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.beloo.widget.chipslayoutmanager.ChipsLayoutManager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.misc.TransactionManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.PublishNormalSingleVideoPage, extras = ARouterConfig.EXTRA_NEED_BINDPHONE | ARouterConfig.EXTRA_NEED_LOGIN)
public class PublishNormalSingleVideoPage extends AppCompatActivity {
    public static final int REQUEST_CODE_SELECT_VIDEO = 1;
    public static final int REQUEST_CODE_SELECT_COVER = 2;
    public static final int REQUEST_CODE_SELECT_INTEREST = 4;
    public static final int REQUEST_CODE_INPUT_COURSE_INTRODUCTION = 10;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.publishBtn)
    TextView publishBtn;
    @BindView(R.id.titleBarLayout)
    ConstraintLayout titleBarLayout;
    @BindView(R.id.titleEt)
    EditText titleEt;
    @BindView(R.id.dividerLine1)
    View dividerLine1;
    @BindView(R.id.inputNumTv)
    TextView inputNumTv;
    @BindView(R.id.maxInputNumTv)
    TextView maxInputNumTv;
    @BindView(R.id.inputNumLayout)
    LinearLayout inputNumLayout;
    @BindView(R.id.locationIv)
    ImageView locationIv;
    @BindView(R.id.locationTv)
    TextView locationTv;
    @BindView(R.id.locationLayout)
    LinearLayout locationLayout;
    @BindView(R.id.interestIv)
    ImageView interestIv;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.interestLayout)
    LinearLayout interestLayout;
    @BindView(R.id.buttonPanel)
    ConstraintLayout buttonPanel;
    @BindView(R.id.roundCornerImageView)
    RoundCornerImageView roundCornerImageView;
    @BindView(R.id.editCoverLayout)
    LinearLayout editCoverLayout;
    @BindView(R.id.durationTv)
    TextView durationTv;
    @BindView(R.id.containerLayout)
    View containerLayout;
    @Autowired
    PublishNormalVideoFormModel formModel = null;
    InputNumFilter inputNumFilter;
    InterestAdapter interestAdapter;
    LocationData locationData = new LocationData();
    CommonBottomDialogFragment locationOptionDialog;
    TrackEvent trackEvent = new TrackEvent();
    BroadcastReceiver receiver;
    @BindView(R.id.interestRv)
    RecyclerView interestRv;
    @BindView(R.id.introductionTv)
    TextView introductionTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_normal_single_video);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        if (formModel == null) {
            ToastX.show(R.string.unknown_error);
            super.finish();
            return;
        }
        init();
        updateView();
        doSelectVideo();
    }

    public void init() {
        interestAdapter = new InterestAdapter();
        interestRv.setLayoutManager(ChipsLayoutManager.newBuilder(this).build());
        interestAdapter.bindToRecyclerView(interestRv);
        interestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    interestAdapter.remove(position);
                } catch (Exception e) {
                }
            }
        });
        inputNumFilter = new InputNumFilter(PublishUtil.MAX_VIDEO_TITLE_LENGTH, false);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                inputNumTv.setText(String.valueOf(num));
            }
        });
        inputNumTv.setText("0");
        maxInputNumTv.setText(String.valueOf(PublishUtil.MAX_VIDEO_TITLE_LENGTH));
        titleEt.setFilters(new InputFilter[]{new ExcludeEnterInputFilter(), new ExcludeEmojiInputFilter(), new ExcludeSpaceInputFilter(), inputNumFilter});
        titleEt.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                for (int i = s.length() - 1; i >= 0; i--) {
                    if (s.charAt(i) == '\n') {
                        s.delete(i, i + 1);
                        return;
                    }
                }
                formModel.setTitle(s.toString());
            }
        });
        titleEt.setOnFocusChangeListener(new EditTextAutoMoveCursorToEndFocusChangeListener());
        locationOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.location_option_dialog)
                .viewIdList(Arrays.asList(R.id.deleteLocationBtn, R.id.relocationBtn, R.id.cancelBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteLocationBtn:
                                locationData = new LocationData();
                                updateView();
                                break;
                            case R.id.relocationBtn:
                                LocationService.startLocation(PublishNormalSingleVideoPage.this, true);
                                break;
                            case R.id.cancelBtn:
                                break;
                        }
                    }
                })
                .build();
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH:
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                            if (locationData.isSuccess()) {
                                updateView();
                            } else {
                                throw new Exception("定位失败");
                            }
                            break;
                    }
                } catch (Exception e) {
                    locationData = new LocationData();
                    locationTv.setText(R.string.click_retry);
                    LocationUtil.showLocationFailedDialog(PublishNormalSingleVideoPage.this);
                }
            }
        };
    }

    @Override
    protected void onPause() {
        containerLayout.requestFocus();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void updateView() {
        if (!TextUtils.isEmpty(formModel.getTitle())) {
            titleEt.setText(formModel.getTitle());
        } else {
            titleEt.setText("");
        }
        interestAdapter.setNewData(formModel.getInterestList());
        if (ListUtil.isEmpty(interestAdapter.getData())) {
            interestRv.setVisibility(View.GONE);
        } else {
            interestRv.setVisibility(View.VISIBLE);
        }
        locationTv.setText(locationData.getCity());
        GlideUtil.with(this)
                .loadCover(formModel.getCoverUrl())
                .into(roundCornerImageView);
        if (ListUtil.isEmpty(formModel.getPublishNormalVideoItemList())) {
            durationTv.setVisibility(View.INVISIBLE);
            editCoverLayout.setVisibility(View.INVISIBLE);
        } else {
            editCoverLayout.setVisibility(View.VISIBLE);
            durationTv.setVisibility(View.VISIBLE);
            durationTv.setText(StringUtils.formatMediaDurationMS(formModel.getPublishNormalVideoItemList().get(0).getDuration()));
        }
        introductionTv.setText(formModel.getCourseIntroduction());
    }

    public void doSelectVideo() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(false)
                .previewVideo(false)
                .enableCrop(false)
                .isCamera(true)
                .compress(false)
                .imageSpanCount(4)
                .maxSize(PublishUtil.MAX_PUBLISH_VIDEO_SIZE)
                .forResult(REQUEST_CODE_SELECT_VIDEO);
    }

    public void doSelectCover() {
        ARouter.getInstance()
                .build(ARouterConfig.SelectVideoCoverPage)
                .withString("videoUrl", formModel.getPublishNormalVideoItemList().get(0).getVideoUrl())
                .navigation(this, REQUEST_CODE_SELECT_COVER);
    }

    public void doPublish() {
        if (!checkFormValidate()) {
            return;
        }
        new CheckSensitiveWordTask(formModel).execute();
    }

    public void executePublish() {
        if (!RxNetTool.isWifi(this) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createPublishBuilder(this)
                    .setPositiveButton(R.string.confirm_upload, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new PublishAsyncTask().execute();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            new PublishAsyncTask().execute();
        }
    }

    public class CheckSensitiveWordTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        PublishNormalVideoFormModel formModel;

        public CheckSensitiveWordTask(PublishNormalVideoFormModel formModel) {
            this.formModel = formModel;
        }

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishNormalSingleVideoPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().checkSensitiveWord(PublishUtil.convertNormalVideoFormModelToMoment(formModel)).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o == null) {
                executePublish();
            } else if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            }
        }
    }


    class PublishAsyncTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(PublishNormalSingleVideoPage.this)
                    .message(R.string.text_process)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        long releaseDate = System.currentTimeMillis();
                        NormalVideoModel normalVideoModel = NormalVideoModel.newBuilder()
                                .id(UUIDUtil.generate())
                                .userId(AccountUtil.getCurrentUser().getId())
                                .releaseDate(releaseDate)
                                .sellDate(releaseDate)
                                .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                .introduction(formModel.getCourseIntroduction())
                                .interest(JSON.toJSONString(formModel.getInterestList()))
                                .industry(JSON.toJSONString(formModel.getIndustryList()))
                                .title(formModel.getTitle())
                                .location(JSON.toJSONString(locationData))
                                .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                .videoNum(formModel.getPublishNormalVideoItemList().size())
                                .build();
                        UploadFile normalVideoCover = UploadFile.newBuilder()
                                .userId(AccountUtil.getCurrentUser().getId())
                                .fileLocalUrl(formModel.getCoverUrl())
                                .storeKey(PublishUtil.generatePhotoFileStoreKey(formModel.getCoverUrl()))
                                .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                .parentId(normalVideoModel.getId())
                                .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                .totalSize(FileUtil.getFileSize(formModel.getCoverUrl()))
                                .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                .build();
                        UploadFileDao.getDao().create(normalVideoCover);
                        normalVideoModel.setCoverStoreKey(normalVideoCover.getStoreKey());
                        normalVideoModel.setCoverUrl(normalVideoCover.getFileLocalUrl());
                        NormalVideoModelDao.getDao().create(normalVideoModel);
                        List<PublishNormalVideoItem> videoItemList = formModel.getPublishNormalVideoItemList();
                        for (PublishNormalVideoItem videoItem : videoItemList) {
                            UploadFile videoCover = UploadFile.newBuilder()
                                    .userId(AccountUtil.getCurrentUser().getId())
                                    .fileLocalUrl(videoItem.getCoverUrl())
                                    .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                    .storeKey(PublishUtil.generatePhotoFileStoreKey(videoItem.getCoverUrl()))
                                    .parentId(normalVideoModel.getId())
                                    .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                    .totalSize(FileUtil.getFileSize(videoItem.getCoverUrl()))
                                    .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                    .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                    .build();
                            UploadFileDao.getDao().create(videoCover);
                            UploadFile video = UploadFile.newBuilder()
                                    .userId(AccountUtil.getCurrentUser().getId())
                                    .fileLocalUrl(videoItem.getVideoUrl())
                                    .fileType(PublishUtil.UPLOAD_FILE_TYPE_VIDEO)
                                    .title(formModel.getTitle())
                                    .storeKey(PublishUtil.generateVideoFileStoreKey(videoItem.getVideoUrl()))
                                    .parentId(normalVideoModel.getId())
                                    .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                    .totalSize(videoItem.getSize())
                                    .duration(videoItem.getDuration())
                                    .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                    .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                    .coverStoreKey(videoCover.getStoreKey())
                                    .coverUrl(videoCover.getFileLocalUrl())
                                    .build();
                            UploadFileDao.getDao().create(video);
                        }
                        return null;
                    }
                });
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                PublishUtil.startPublish();
                ToastX.show(R.string.publishing_normal_video);
                PublishNormalSingleVideoPage.super.finish();
                PublishUtil.jumpToDMPage(PublishNormalSingleVideoPage.this);
            }
        }
    }


    @Override
    public void finish() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PublishNormalSingleVideoPage.super.finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }

    @OnClick({R.id.introductionLayout, R.id.roundCornerImageView, R.id.titleBackBtn, R.id.publishBtn, R.id.locationLayout, R.id.interestLayout, R.id.editCoverLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.roundCornerImageView:
                doSelectVideo();
                break;
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.publishBtn:
                doPublish();
                break;
            case R.id.locationLayout:
                locationOptionDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.interestLayout:
//                if (formModel.getInterestList().size() >= InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM) {
//                    ToastX.show(StringUtils.getString(R.string.reach_max_select_interest_num_warning, InterestUtil.MAX_SELECTED_PUBLISH_INTEREST_NUM));
//                    return;
//                }
                ARouter.getInstance()
                        .build(ARouterConfig.SelectPublishInterestPage)
                        .withObject("selectedInterestList", formModel.getInterestList())
                        .withObject("publishIndustryList", formModel.getIndustryList())
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                break;
            case R.id.editCoverLayout:
                doSelectCover();
                break;
            case R.id.introductionLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.InputIntroductionPage)
                        .withString("text", formModel.getCourseIntroduction())
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_INTRODUCTION);
                break;
        }
    }

    public boolean checkFormValidate() {
        if (TextUtils.isEmpty(formModel.getTitle())) {
            ToastX.show(R.string.title_can_not_empty);
            return false;
        }
        if (ListUtil.isEmpty(formModel.getInterestList())) {
            ToastX.show(R.string.interest_can_not_empty);
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_INPUT_COURSE_INTRODUCTION:
                if (resultCode == RESULT_OK) {
                    formModel.setCourseIntroduction(data.getStringExtra(InputIntrodutionPage.EXTRA_KEY_INPUT_STRING));
                    updateView();
                }
                break;
            case REQUEST_CODE_SELECT_COVER:
                if (resultCode == RESULT_OK) {
                    PublishNormalVideoItem publishLearnVideoItem = formModel.getPublishNormalVideoItemList().get(0);
                    publishLearnVideoItem.setCoverUrl(data.getStringExtra(SelectVideoCoverPage.EXTRA_KEY_VIDEO_COVER_URL));
                    formModel.setCoverUrl(data.getStringExtra(SelectVideoCoverPage.EXTRA_KEY_VIDEO_COVER_URL));
                    updateView();
                    trackEvent.sendEvent(this, TrackEvent.FIN_SELECT_NORMAL_VIDEO_COVER, TrackEvent.FIN_SELECT_NORMAL_VIDEO_COVER_LABEL);
                    {
                        Map<String, String> attrs = new HashMap<>();
                        attrs.put("action_type", "2");
                        trackEvent.sendEvent(this, TrackEvent.NORMAL_VIDEO_MOD_SUB_VIDEO_ACT, TrackEvent.NORMAL_VIDEO_MOD_SUB_VIDEO_ACT_LABEL, attrs, true);
                    }
                } else {
                    trackEvent.sendEvent(this, TrackEvent.UNSEL_NORMAL_VIDEO_SUB_COVER, TrackEvent.UNSEL_NORMAL_VIDEO_SUB_COVER_LABEL);
                }
                break;
            case REQUEST_CODE_SELECT_VIDEO:
                if (resultCode == RESULT_OK) {
                    if (ListUtil.isEmpty(formModel.getPublishNormalVideoItemList())) {
                        IntentFilter intentFilter = new IntentFilter();
                        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
                        registerReceiver(receiver, intentFilter);
                        LocationService.startLocation(this);
                    }
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        List<PublishNormalVideoItem> publishLearnVideoItemList = new LinkedList<>();
                        for (LocalMedia localMedia : selectList) {
                            publishLearnVideoItemList.add(PublishNormalVideoItem.newBuilder()
                                    .videoUrl(localMedia.getPath())
                                    .duration(localMedia.getDuration())
                                    .size(FileUtil.getFileSize(localMedia.getPath()))
                                    .build());
                            String mediaSource = TrackUtil.detectMediaSource(localMedia.getPath());
                            switch (mediaSource) {
                                case TrackUtil.MEDIA_SOURCE_CAMERA_SHOT: {
                                    trackEvent.sendEvent(this, TrackEvent.NORMAL_VIDEO_ADD_RECORD_VIDEO, TrackEvent.NORMAL_VIDEO_ADD_RECORD_VIDEO);
                                    break;
                                }
                                case TrackUtil.MEDIA_SOURCE_ALBUM: {
                                    trackEvent.sendEvent(this, TrackEvent.NORMAL_VIDEO_ADD_NO_REC_VIDEO, TrackEvent.NORMAL_VIDEO_ADD_NO_REC_VIDEO);
                                    break;
                                }
                            }
                        }
                        new AsyncTask<List<PublishNormalVideoItem>, Object, List<PublishNormalVideoItem>>() {
                            LoadingDialog loadingDialog;

                            @Override
                            protected void onPreExecute() {
                                loadingDialog = LoadingDialog.newBuilder()
                                        .with(PublishNormalSingleVideoPage.this)
                                        .message(R.string.text_process)
                                        .show();
                            }

                            @Override
                            protected List<PublishNormalVideoItem> doInBackground(List<PublishNormalVideoItem>... params) {
                                List<PublishNormalVideoItem> itemList = params[0];
                                for (PublishNormalVideoItem item : itemList) {
                                    item.setCoverUrl(VideoUtil.getVideoCover(item.getVideoUrl(), 0));
                                }
                                return itemList;
                            }

                            @Override
                            protected void onPostExecute(List<PublishNormalVideoItem> list) {
                                loadingDialog.dismiss();
                                formModel.setCoverUrl(list.get(0).getCoverUrl());
                                formModel.getPublishNormalVideoItemList().clear();
                                formModel.getPublishNormalVideoItemList().addAll(list);
                                updateView();
                            }
                        }.execute(publishLearnVideoItemList);
                    }
                } else {
                    if (ListUtil.isEmpty(formModel.getPublishNormalVideoItemList())) {
                        super.finish();
                    }
                }
                break;
            case REQUEST_CODE_SELECT_INTEREST:
                if (resultCode == RESULT_OK) {
                    List<Interest> interestList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INTEREST_DATA);
                    List<Interest> industryList = data.getParcelableArrayListExtra(SelectPublishInterestPage.ACTION_INDUSTRY_DATA);
                    formModel.setInterestList(interestList);
                    formModel.setIndustryList(industryList);
                    updateView();
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }

    }
}
